<template>
  <div class="login-page">
    <div class="box-card">
      <div class="title">登录您的帐户</div>
      <el-form ref="ruleFormRef"
               :model="userForm"
               :rules="rules"
               label-position="top"
               label-width="100px">
        <el-form-item label="用户名"
                      prop="userName">
          <el-input v-model.trim="userForm.userName"
                    autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model.trim="userForm.password"
                    autocomplete="off"
                    show-password
                    type="password"
                    @keyup.enter="onSubmit" />
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading"
                     style="flex: 1;"
                     type="primary"
                     @click="onSubmit">登录1</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";

const store = useStore();
const router = useRouter();
const ruleFormRef = ref<FormInstance>();
const loading = ref(false);
const rules = reactive<FormRules>({
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});
const userForm = reactive({
  userName: "",
  password: "",
});

const onSubmit = () => {
  ruleFormRef.value?.validate((valid) => {
    if (valid) {
      loading.value = true;
      store
        .dispatch("user/login", userForm)
        .then(() => {
          getUserMenu();
        })
        .catch((err) => {
          loading.value = false;
          ElMessage.error(err.message || "登录失败");
        });
    }
  });
};
const getUserMenu = () => {
  store
    .dispatch("menu/getMenu")
    .then(() => {
      loading.value = false;
      ElMessage.success("登录成功！");
      router.push({ path: "/" });
    })
    .catch(() => {
      loading.value = false;
      router.push({ path: "/403" });
    });
};
</script>

<style scoped lang="less">
.login-page {
  width: 100%;
  height: 100%;
  background: url("~@/assets/images/login-bg.svg") no-repeat center / contain;
  overflow: hidden;
  .title {
    text-align: center;
    font-size: 18px;
    margin-bottom: 25px;
    font-weight: 600;
  }
  .box-card {
    box-shadow: 0 0 12px rgb(0 0 0 / 12%);
    max-width: 450px;
    min-width: 420px;
    padding: 30px 40px;
    box-sizing: border-box;
    border-radius: 4px;
    margin: 18% auto 0;
  }
}
</style>
